{
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
}

unit InputString;

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  ExtCtrls, VisualUtils, Math;

type
  TStringValidator = function(const s: String): Boolean of object;

  TInputStringForm = class(TForm)
    btnOk: TButton;
    btnCancel: TButton;
    edtValue: TEdit;
    lblPrompt: TLabel;
    pnlButtons: TPanel;
    procedure edtValueChange(Sender: TObject);
  private
    FValidator: TStringValidator;
    procedure UpdateUi;
    { private declarations }
  public
    class function OpenModal(const Caption, Prompt: String; var Value: String;
      MaxLength: Integer; const Validator: TStringValidator = nil;
      const OkCaption: String = ''): Boolean;
    { public declarations }
  end;

implementation

{$R *.lfm}

{ TInputStringForm }

procedure TInputStringForm.edtValueChange(Sender: TObject);
begin
  UpdateUi;
end;

procedure TInputStringForm.UpdateUi;
var
  Ok: Boolean;
begin
  if Assigned(FValidator) then
    Ok := FValidator(edtValue.Text)
  else
    Ok := TRUE;
  btnOk.Enabled := Ok;
end;

class function TInputStringForm.OpenModal(const Caption, Prompt: String;
  var Value: String; MaxLength: Integer; const Validator: TStringValidator;
  const OkCaption: String): Boolean;
var
  Form: TInputStringForm;
begin
  Form := TInputStringForm.Create(nil);
  try
    Form.HandleNeeded;

    Form.Caption := Caption;
    Form.lblPrompt.Caption := Prompt;
    Form.edtValue.Text := Value;
    Form.edtValue.MaxLength := MaxLength;
    Form.edtValue.Constraints.MinWidth := Form.Canvas.TextWidth('A')
      * Min(MaxLength, 50);
    Form.FValidator := Validator;

    if OkCaption <> '' then
      Form.btnOk.Caption := OkCaption;
    StretchToWidest([Form.btnOk, Form.btnCancel]);

    Form.UpdateUi;
    Result := Form.ShowModal = mrOk;

    if Result then
      Value := Form.edtValue.Text;
  finally
    Form.Free;
  end;
end;

end.

